package cn.iocoder.yudao.module.vos.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.vos.job.PushListDispatchJob;
import cn.iocoder.yudao.module.vos.job.vo.PushItem;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class InterfaceAClient {

    @Value("${94waihu.api.appKey}")
    private String apiAppKey;

    @Value("${94waihu.api.appSecret}")
    private String apiAppSecret;

    @Value("${94waihu.api.endpoint}")
    private String apiEndpoint;
    /**
     * 发送请求到 94AI 接口
     * @param requestId 请求ID
     * @param taskId 任务ID
     * @param failReturn 失败返回类型
     * @param items 待发送的 PushItem 列表
     * @return 响应信息
     */
    public String sendToInterfaceA(String requestId , String failReturn, List<PushItem> items ,String taskId) {
        Map<String, Object> params = new HashMap<>();
        params.put("requestId", requestId);
        params.put("taskId", taskId);
        params.put("failReturn", failReturn);

        // 转换 customers 为接口所需格式
        params.put("customers", convertItemsToCustomers(items));

        String body = JSONUtil.toJsonStr(params);
//        String encryptedBody = encryptRequestBody(body);

        // 设置请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", apiAppKey);
        headers.put("timestamp", String.valueOf(System.currentTimeMillis()));
        headers.put("sign", generateSign(headers.get("timestamp")));
        headers.put("Content-Type", "application/json");

        // 发送请求
        String response = HttpRequest.post(apiEndpoint + "/v1/task/importTaskCustomer")
                .addHeaders(headers)
                .body(body)
                .execute()
                .body();

        return response;
    }

    /**
     * 将 PushItem 转换为符合接口要求的 customers 格式
     */
    private List<Map<String, Object>> convertItemsToCustomers(List<PushItem> items) {
        List<Map<String, Object>> customers = CollUtil.newArrayList();

        for (PushItem item : items) {
            Map<String, Object> customer = new HashMap<>();
            customer.put("number", item.getPhoneE164());
            customer.put("numberMD5", item.getPhoneMd5());
            customer.put("tag", item.getPhoneTags());
            customer.put("properties", new HashMap<>());  // properties 为空对象
            customers.add(customer);
        }

        return customers;
    }

    /**
     * 对请求体进行加密
     */
    private String encryptRequestBody(String body) {
        // AES CBC加密，使用 appSecret 和时间戳作为加密 key 和 IV
        String timestamp = String.valueOf(System.currentTimeMillis());
        String iv = new StringBuilder(timestamp).reverse().toString();

        // 使用 AES CBC PKCS5PADDING 加密
        return SecureUtil.aes(apiAppSecret.getBytes())
                .setIv(iv.getBytes())
                .encryptHex(body);
    }

    /**
     * 生成签名，使用 HMAC-SHA1 签名方式
     */
    private String generateSign(String timestamp) {
        return ApiKit.getSign(apiAppKey, apiAppSecret, timestamp);
    }

    public static void main(String[] args) {
        String appKey = "37c577a014ef1410";
        String appSecret = "583565a044f4364b5ea9e0954d0f5240";
        String timestamp = "1642040026243";
        String sign = ApiKit.getSign(appKey,appSecret,timestamp);
        System.out.println("sign: " + sign);
    }
}
